package com.cdxy.util;

import com.cdxy.enums.BizErrorEnum;
import com.cdxy.enums.redis.RedisCacheGroupEnum;
import com.cdxy.model.dto.base.exception.BusinessException;
import com.cdxy.model.dto.base.redis.RedisCacheManager;
import com.cdxy.model.dto.resp.UserInfoResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Author: tangy
 * @Date: 2020/3/11 10:52
 */
@Component
public class AxUidUtil {

    @Autowired
    private RedisCacheManager redisCacheManager;


    public Integer getAxUid() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String authorization = attributes.getRequest().getHeader("Authorization");
        UserInfoResp userInfoResp = (UserInfoResp) redisCacheManager.get(RedisCacheGroupEnum.LOGIN_SUCCESS_TOKEN, authorization);
        if (userInfoResp == null) {
            throw new BusinessException(BizErrorEnum.LOGIN_NO_TOKEN);
        }
        return userInfoResp.getAxUid();
    }


    public Integer getAxUidNotForce() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String authorization = attributes.getRequest().getHeader("Authorization");
        UserInfoResp userInfoResp = (UserInfoResp) redisCacheManager.get(RedisCacheGroupEnum.LOGIN_SUCCESS_TOKEN, authorization);
        if (userInfoResp == null) {
            return null;
        }
        return userInfoResp.getAxUid();
    }

}
